﻿using System;
using System.Collections;
using System.Collections.Generic;
using Flagwind.Services;
using Flagwind.Resources;
using Flagwind.Runtime.Serialization;

namespace Flagwind.Collections.Commands
{
	[CommandOption("count", Type = typeof(int), DefaultValue = 1, Description = "${Text.QueueCommand.Options.Count}")]
	[CommandOption("queues", Type = typeof(string), Description = "${Text.QueueCommand.Options.Queues}")]
	public class QueuePeekCommand : CommandBase<CommandContext>
	{
		#region 构造方法

		public QueuePeekCommand() : this("Peek")
		{
		}

		public QueuePeekCommand(string name) : base(name)
		{
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(CommandContext context)
		{
			var count = context.Expression.Options.GetValue<int>("count");
			var result = new List<object>(count);

			if(count < 1)
			{
				throw new CommandOptionValueException("count", count);
			}

			var queues = QueueCommandHelper.GetQueues(context.CommandNode, context.Expression.Options.GetValue<string>("queues"));

			foreach(var queue in queues)
			{
				if(queue.Count == 0)
				{
					context.Output.WriteLine(CommandOutletColor.DarkRed, ResourceUtility.GetString("Text.QueueIsEmpty", queue.Name));
					continue;
				}

				var items = queue.Peek(count);

				if(items == null)
				{
					break;
				}

				foreach(var item in items)
				{
					result.Add(item);
				}

				context.Output.WriteLine(Serializer.Text.Serialize(items));
			}

			return result.ToArray();
		}

		#endregion
	}
}